package com.iyao_app.mvp.guide;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.DisplayMetrics;
import android.view.WindowManager;
import android.widget.RelativeLayout;

import com.iyao_app.R;
import com.iyao_app.base.BaseActivity;
import com.iyao_app.entry.User;
import com.iyao_app.mvp.home.MainActivity;
import com.iyao_app.mvp.login.LoginActivity;
import com.iyao_app.util.Contants;
import com.iyao_app.util.DbUtil;
import com.iyao_app.util.FileUtil;
import com.iyaowoqu.base_library.util.LogUtil;
import com.iyaowoqu.base_library.util.SPUtils;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;
import com.yanzhenjie.permission.PermissionNo;
import com.yanzhenjie.permission.PermissionYes;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * 作者 : 胡家兵
 * 时间 : 2017/11/9.
 */

public class GuideActivity extends BaseActivity {


    @BindView(R.id.rl_root)
    RelativeLayout mRlRoot;
    private Bitmap bm;
    private final int REQUEST_CODE_STORAGE = 100;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);  //全屏
        setContentView(R.layout.activity_guide);
        ButterKnife.bind(this);
        bm = BitmapFactory.decodeResource(this.getResources(), R.mipmap.guide_image);
        BitmapDrawable bd = new BitmapDrawable(this.getResources(), bm);
        mRlRoot.setBackgroundDrawable(bd);

        // Activity:
        AndPermission.with(this)
                .requestCode(REQUEST_CODE_STORAGE)
                .permission(Permission.STORAGE)
                .rationale(new RationaleListener() {
                    @Override
                    public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
                        // 这里的对话框可以自定义，只要调用rationale.resume()就可以继续申请。
                        AndPermission.rationaleDialog(GuideActivity.this, rationale).show();
                    }
                })
                .callback(this)
                .start();

        DisplayMetrics metrics = new DisplayMetrics();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            getWindowManager().getDefaultDisplay().getRealMetrics(metrics);
            int width = metrics.widthPixels;
            int heightPixels = metrics.heightPixels;
            float density = metrics.densityDpi;
            LogUtil.e(density+"===width=="+width+"==heightPixels=="+heightPixels);
        }
        int screenWidth = getWindowManager().getDefaultDisplay().getWidth();//真实分辨率 宽
        int screenHeight = getWindowManager().getDefaultDisplay().getHeight();//真实分辨率 高
        DisplayMetrics dm = new DisplayMetrics();
        dm = getResources().getDisplayMetrics();
        int densityDPI = dm.densityDpi;     // 屏幕密度（每寸像素：120(ldpi)/160(mdpi)/213(tvdpi)/240(hdpi)/320(xhdpi)）
        LogUtil.e("===="+"真实分辨率："+screenWidth+"*"+screenHeight+"  每英寸:"+densityDPI);
    }


    @PermissionYes(REQUEST_CODE_STORAGE)
    private void getMultiYes(@NonNull List<String> grantedPermissions) {
        LogUtil.e("成功");
        if (haveData()) {//有
            enter();
        } else {
            blackMap();
        }
    }

    @PermissionNo(REQUEST_CODE_STORAGE)
    private void getMultiNo(@NonNull List<String> deniedPermissions) {
        LogUtil.e("failure");
        // 用户否勾选了不再提示并且拒绝了权限，那么提示用户到设置中授权。
        if (AndPermission.hasAlwaysDeniedPermission(this, deniedPermissions)) {
            AndPermission.defaultSettingDialog(this, 100)
                    .setTitle("权限申请失败")
                    .setMessage("我们需要的一些权限被您拒绝或者系统发生错误申请失败，请您到设置页面手动授权，否则功能无法正常使用！")
                    .setPositiveButton("好，去设置")
                    .setNegativeButton("拒绝", null)
                    .show();

        }
    }

    private void blackMap() {
        //观察者模式,这里产生事件,事件产生后发送给接受者,但是一定要记得将事件的产生者和接收者捆绑在一起,否则会出现错误
        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> e) throws Exception {
                LogUtil.e("==1=" + Thread.currentThread().getName());
                LogUtil.e("===subscribe==");
                //进行JSON的文件读取然后写入到本地
                InputStream in = null;
                File file = null;
                OutputStream os = null;
                try {
                    FileUtil.createFile("style");
                    in = getResources().getAssets().open("mystyle_sdk_1511952973_0100.data");

                    file = new File(Environment.getExternalStorageDirectory()
                            + File.separator + "style/" + "mystyle_sdk_1511952973_0100.data");
                    os = new FileOutputStream(file);
                    //创建byte数组
                    byte[] buffer = new byte[1024];
                    int length = -1;
                    while ((length = in.read(buffer)) != -1) {
                        os.write(buffer, 0, length);
                    }
                    // clear cache
                    os.flush();
                    os.close();
                    in.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                    try {
                        if (os != null) {
                            os.close();
                        }
                        if (in != null) {
                            in.close();
                        }
                    } catch (Exception e1) {
                        e1.printStackTrace();
                    }
                } finally {
                    try {
                        if (os != null) {
                            os.close();
                        }
                        if (in != null) {
                            in.close();
                        }
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }
                e.onComplete();
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    //接受者,根据事件产生者产生的事件调用不同方法
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(String value) {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {
                        enter();
                    }
                });
    }

    private void enter() {
        Observable.timer(2, TimeUnit.SECONDS).subscribe(new Consumer<Long>() {

            @Override
            public void accept(Long aLong) throws Exception {
                boolean isFirst = SPUtils.getInstance().getBoolean(Contants.IS_FIRST, true);
                if (isFirst) {
                    enterSplash();
                } else {

                    User user = DbUtil.getUser();
                    if (user == null) {
                        LogUtil.e("====空的===");
                        enterLogin();
                    } else {
                        LogUtil.e("====userInfo===" + user.id + "===" + user.toString());
                        enterMain();
                    }
                }
            }
        });
    }

    private boolean haveData() {
        try {
            File f = new File(Environment.getExternalStorageDirectory()
                    + File.separator + "style/mystyle_sdk_1511952973_0100.data");
            if (!f.exists()) {
                return false;
            }

        } catch (Exception e) {
            // TODO: handle exception
            return false;
        }
        return true;
    }

    private void enterMain() {
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
        finish();
    }

    private void enterLogin() {
        Intent intent = new Intent(this, LoginActivity.class);
        startActivity(intent);
        finish();
    }

    private void enterSplash() {
        Intent intent = new Intent(this, SplashActivity.class);
        startActivity(intent);
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        BitmapDrawable bd = (BitmapDrawable) mRlRoot.getBackground();
        bm = null;
        mRlRoot.setBackgroundDrawable(null);
        bd.setCallback(null);
        bd.getBitmap().recycle();
    }
}
